/*日志记录*/  
#include "writelog.h"
  
 
int file_fd = -1;  
int old_day = 0;
int log_file(switch_mode mode)  
{  
    char file_path[512] = {0};  
    struct tm tm_time;  
    time_t t_log;  
    std::string log_time = "";  
  
    assert(getcwd(file_path, 512) != NULL);    //当前目录  
    if (file_path[strlen(file_path) - 1] != '/') {  
        file_path[strlen(file_path)] = '/';  
    }  
    if(access(file_path, F_OK) != 0) {     //目录不存在  
        std::string build_path ="mkdir -p ";  
        build_path += file_path;  
        assert(system(build_path.c_str()) !=0 );  
    }  
  
    t_log = time(NULL);  
    localtime_r(&t_log, &tm_time);  
    sprintf(file_path,"log_%d.log",tm_time.tm_mday % 3);
	old_day = tm_time.tm_mday; 
    file_fd = open(file_path, O_RDWR|O_CREAT|O_APPEND, 0666);  
    assert(file_fd != -1);  
    return 0;  
}  
void write_cmd(const char *fmt,...)  
{  
    va_list ap;  
    va_start(ap,fmt);  
    vprintf(fmt,ap);  
    va_end(ap);  
}  
int write_log(const char *msg, ...)  
{  
    char final[2048] = {0};   //当前时间记录  
    va_list vl_list;  
    va_start(vl_list, msg);  
    char content[10240] = {0};  
    vsprintf(content, msg, vl_list);   //格式化处理msg到字符串  
    va_end(vl_list);  
  
    time_t  time_write;  
    struct tm tm_log;  
    time_write = time(NULL);        //日志存储时间  
    localtime_r(&time_write, &tm_log);  
    if(tm_log.tm_mday != old_day)
	{
		char file_path[512] = {0};
		sprintf(file_path,"log_%d.log",tm_log.tm_mday % 3);
		old_day = tm_log.tm_mday;
		if((access(file_path,F_OK))!=-1)   
		{   
			printf("文件%s存在.\n",file_path);   
			remove(file_path);
		}
	   
		file_fd = open(file_path, O_RDWR|O_CREAT|O_APPEND, 0666); 
	}
	
	strftime(final, sizeof(final), "[%Y-%m-%d %H:%M:%S] ", &tm_log);  
  
    strncat(final, content, strlen(content));  
    assert(msg != NULL && file_fd != -1);  
    assert( write(file_fd, final, strlen(final)) == (int)strlen(final));  
    return 0;  
}  
void close_file()  
{  
    close(file_fd);  
}  
/******************日志记录测试******************/  
/*int main()  
{  
    log_file();  
    write_cmd("the address for cmd:%d\n", 100);  
    write_log("the address for log:%d\n", 200);  
    close_file();  
    return 0;  
} */
